# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.osv import expression
from odoo.tools import float_compare
from odoo.addons import decimal_precision as dp

class MrpProductionRetrun(models.Model):
    _inherit = 'mrp.production'
    return_picking_ids = fields.One2many('stock.picking', 'return_raw_production_id', string=u'退料单')

class StockPicking(models.Model):
    _inherit = 'stock.picking'

    return_raw_production_id = fields.Many2one(string=u'制造订单', comodel_name='mrp.production')


class StockMove(models.Model):
    _inherit = 'stock.move'

    return_raw_production_id = fields.Many2one(string=u'制造订单', comodel_name='mrp.production')




class MrpReturnRawWizard(models.TransientModel):
    _name = 'mrp.return.raw.wizard'

    @api.model
    def default_raw_return_ids(self):
        production_id = self._context.get('return_raw_production_id')
        mo = self.env['mrp.production'].browse(production_id)
        # products = mo.move_raw_ids.mapped('product_id')
        vals = []
        for p in mo.consume_line_ids:
            vals.append([0, 0, {
                'product_id': p.product_id.id,
                'product_qty': 0,
                'max_return_qty': p.picking_qty - p.return_qty - p.consume_qty-p.scrap_qty
            }])
        return vals

    production_id = fields.Many2one(string=u'制造订单', comodel_name='mrp.production')
    raw_return_ids = fields.One2many(string=u'补领明细', comodel_name='mrp.return.raw.line', inverse_name='return_id', default=default_raw_return_ids)

    def confirm_to_return_raw(self):
        line_vaild = self.raw_return_ids.filtered(lambda x: x.product_qty > 0)
        # picking = self.create_picking()
        stock_move = self.env["stock.move"].with_context({})
        location_data = {}
        for line in line_vaild:
            if float_compare(line.max_return_qty, line.product_qty, precision_rounding=2) < 0:
                raise UserError(u'%s 超过最大可退回数量' % line.product_id.name)

            rule = line._find_suitable_rule()
            print (rule.location_src_id.name)
            if not rule:
                raise UserError(u'%s 找不到对应的路线' % line.product_id.name)
            else:
                if not location_data.get(rule.location_src_id.id):
                    location_data[rule.location_src_id.id] = line
                else:
                    location_data[rule.location_src_id.id] += line

        #根据有几个位置 生成几张picking
        # self.production_id.button_unreserve()
        pickings = self.env['stock.picking']
        for location_id in location_data.keys():
            group = self.create_procurement_group()
            picking = self.create_picking(location_id, group)
            lines = location_data[location_id]
            for line in lines:
                vals = line.create_move_vals(picking)
                vals['group_id'] = group.id
                move = stock_move.create(vals)
                move._action_confirm()
                move._action_assign()

            picking.action_confirm()
            pickings += picking
        self.production_id.action_assign()
        if self._context.get('mark_done_scrap', False):
            self.production_id.scrap_confirm = True
            # 当前新生成的不取消
            (self.production_id.get_return_picking().filtered(lambda x: x.state not in ['done', 'cancel']) - pickings).action_cancel()

    def create_picking(self, location_id, group):
        warehouse_id = self.production_id.picking_type_id.warehouse_id
        if not warehouse_id:
            raise UserError(u'该作业类型未设置对应仓库')
        chose_warehouse = self.env['stock.warehouse']
        warehouses = self.env['stock.warehouse'].search([])
        for warehouse in warehouses:
            if warehouse.lot_stock_id.id == location_id:
                chose_warehouse = warehouse
        # if not chose_warehouse:
        #     raise UserError(u'位置必须是库存库位')
        picking_type_2=self.env['stock.picking.type'].search([('return_type','=','return_raw')])
        # picking_type_2 = self.env["stock.picking.type"].search([('return_type', '=', 'return_raw_step_2'),
        #                                                       ('warehouse_id', '=', chose_warehouse.id)],
        #                                                      limit=1)
        # repicking_lot_id = self.env['procurement.rule'].search([('location_id', '=', self.production_id.location_src_id.id)], limit=1).location_src_id
        # if not repicking_lot_id:
        #     raise UserError(u'未找到退回领料区')

        if not picking_type_2:
            raise UserError(u'未找到对应的退料调拨类型')

        pick = self.env['stock.picking'].search([('picking_type_id', '=', picking_type_2.id),
                                                     ('group_id', '=', group.id),
                                                     ('location_dest_id', '=',location_id)], limit=1)

        if not pick:
            vals = {
                'picking_type_id': picking_type_2.id,
                'group_id': group.id,
                # 'internal_picking_id': self.id,
                # 'partner_id': self.partner_id.id,
                'return_raw_production_id': self.production_id.id,
                'date': fields.datetime.now(),
                'origin': u'退料 ' + self.production_id.name,
                'location_dest_id': location_id,
                'location_id': self.production_id.location_src_id.id,
            }
            pick = self.env['stock.picking'].with_context({}).create(vals)
        return pick

        # vals = {
        #     'picking_type_id': picking_type_2.id,
        #     # 'internal_picking_id': self.id,
        #     # 'partner_id': self.partner_id.id,
        #     'return_raw_production_id': self.production_id.id,
        #     'date': fields.datetime.now(),
        #     'origin': u'退料 ' + self.production_id.name,
        #     'location_dest_id': lot_stock_id.id,
        #     'location_id': self.production_id.location_src_id.id,
        # }
        # # vals_2 = {
        # #     'picking_type_id': picking_type_2.id,
        # #     # 'internal_picking_id': self.id,
        # #     # 'partner_id': self.partner_id.id,
        # #     'return_raw_production_id': self.production_id.id,
        # #     'date': fields.datetime.now(),
        # #     'origin': u'退料 ' + self.production_id.name,
        # #     'location_dest_id': lot_stock_id.id,
        # #     'location_id': repicking_lot_id.id,
        # # }
        # picking = self.env['stock.picking'].with_context({}).create(vals)
        # # picking_step_2 = self.env['stock.picking'].with_context({}).create(vals_2)
        # return picking  # , picking_step_2

    def create_procurement_group(self):
        return self.env['procurement.group'].create({
            'name': self.production_id.name + u'-退料'
        })

class MrpReturnRawLine(models.TransientModel):
    _name = 'mrp.return.raw.line'

    return_id = fields.Many2one(string=u'补领单', comodel_name='mrp.return.raw.wizard')
    product_id = fields.Many2one(string=u'产品', comodel_name='product.product')
    product_qty = fields.Float(string=u'数量', digits=dp.get_precision('Product Unit of Measure'))
    max_return_qty = fields.Float(string=u'最大可退数量', readonly=True, digits=dp.get_precision('Product Unit of Measure'))

    def create_move_vals(self, picking):
        self.ensure_one()
        return {
            'name': self.return_id.production_id.name + u'- 退料 -' + self.product_id.name,
            'product_id': self.product_id.id,
            'product_uom': self.product_id.uom_id.id,
            'date': picking.date,
            'date_expected': picking.date,
            'location_id': picking.location_id.id,
            'location_dest_id': picking.location_dest_id.id,
            'picking_id': picking.id,
            'state': 'draft',
            'quantity_done':self.product_qty,
            'picking_type_id': picking.picking_type_id.id,
            'origin': picking.name,
            'warehouse_id': picking.picking_type_id.warehouse_id.id,
            'product_uom_qty': self.product_qty,
            'return_raw_production_id': picking.return_raw_production_id.id,
        }

    def _find_suitable_rule(self):
        res = self.env['stock.rule']

        product_routes = self.product_id.route_ids | self.product_id.categ_id.total_route_ids
        if product_routes:
            res = res.search(expression.AND([[('route_id', 'in', product_routes.ids)], [
                ('location_id', 'in', [self.return_id.production_id.location_src_id.id])]]),
                              order='route_sequence, sequence', limit=1)
            # res = res.search(expression.AND([[('route_id', 'in', product_routes.ids)],
            #                                   [('location_id', 'in', [res.location_src_id.id])]]),
            #                   order='route_sequence, sequence', limit=1)  # 根据路线查找到 对应库存的rule

        return res
